﻿/*******************************************************************************
 * Copyright @ 2017 YunSpace.Framework 版权所有
 * Author: GaoTang
 * Description: YunSpace 快速开发平台
 * Website：http://www.yunspace.com.cn
*********************************************************************************/
#region USING SYSTEM
using YunSpace.Core;
using YunSpace.Domain.Entity.SiteLibraryManage;
using YunSpace.Domain.IRepository.SiteLibraryManage;
using YunSpace.Repository.SiteLibraryManage;
using System.Collections.Generic;
using System.Linq;
using System;
using YunSpace.Data;
using YunSpace.Domain.Entity.SystemManage;
using YunSpace.Domain._02_ViewModel.SiteLibraryManage;
using YunSpace.ThirdService;
#endregion

namespace YunSpace.Application.SiteLibraryManage
{
    public class SupplierApp
    {
        private ISupplierRepository service = new SupplierRepository();

        public List<SupplierEntity> GetList(Pagination pagination, string queryJson)
        {
            var expression = ExtLinq.True<SupplierEntity>();
            var queryParam = queryJson.ToJObject();
            if (!queryParam["keyword"].IsEmpty())
            {
                string keyword = queryParam["keyword"].ToString();
                expression = expression.And(t => t.name.Contains(keyword));
            }
            // if (!queryParam["timeType"].IsEmpty())
            // {
            //     string timeType = queryParam["timeType"].ToString();
            //     DateTime startTime = DateTime.Now.ToString("yyyy-MM-dd").ToDate();
            //     DateTime endTime = DateTime.Now.ToString("yyyy-MM-dd").ToDate().AddDays(1);
            //     switch (timeType)
            //     {
            //         case "1":
            //             break;
            //         case "2":
            //             startTime = DateTime.Now.AddDays(-7);
            //             break;
            //         case "3":
            //             startTime = DateTime.Now.AddMonths(-1);
            //             break;
            //         case "4":
            //             startTime = DateTime.Now.AddMonths(-3);
            //             break;
            //         default:
            //             break;
            //     }
            //     expression = expression.And(t => t.F_Date >= startTime && t.F_Date <= endTime);
            // }
            return service.FindList(expression, pagination);
        }

        public SupplierEntity GetForm(string keyValue)
        {
            return service.FindEntity(keyValue);
        }
        public void DeleteForm(string keyValue)
        {
            service.Delete(t => t.F_Id == keyValue);
        }

        public void UpdateForm(SupplierEntity supplier)
        {
            service.Update(supplier);
        }
        public void SubmitForm(SupplierEntity supplierEntity, string keyValue)
        {
            if (!string.IsNullOrEmpty(keyValue))
            {
                supplierEntity.Modify(keyValue);
                service.Update(supplierEntity);
            }
            else
            {
                supplierEntity.Create();
                // supplierEntity.F_Category = 2;
                service.Insert(supplierEntity);
            }
        }

        public List<SupplierEntity> GetSupplierName(string F_Id)
        {
            return service.GetSupplierName(F_Id);
        }

        public void SendCode(string Phone, out string Code)
        {
            var random = new Random();
            Code = random.Next(10000).ToString().PadLeft(4, '0');
            WebHelper.WriteSession(Phone, Code);
            RongLianSmsManger sms = new RongLianSmsManger();
            sms.SendCode(Phone, new string[] { Code });
        }

        public void SendRegisterCode(string Phone, out string Code)
        {
            var random = new Random();
            Code = random.Next(10000).ToString().PadLeft(4, '0');
            WebHelper.WriteSession(Phone, Code);
            RongLianSmsManger sms = new RongLianSmsManger();
            sms.SendRegisterCode(Phone, new string[] { Code });
        }

        public SupplierEntity CheckSupplier(string Phone, out string roleid)
        {
            roleid = "";
            using (var db = new RepositoryBase())
            {
                string sql = $@"SELECT * FROM SL_Contact T WHERE T.Phone='{Phone}' AND (T.F_DeleteMark is null or T.F_DeleteMark=0)";
                var Contact = db.FindList<SLContactEntity>(sql);
                if (Contact == null || Contact.Count == 0)
                {
                    var Site = db.IQueryable<SiteEntity>(t => t.F_phone == Phone).FirstOrDefault();
                    if (Site != null)
                    {
                        var Supplier = Site.F_SupplierId;
                        var rid = "2001";
                        var Role_ = db.IQueryable<RoleEntity>(s => s.F_EnCode == rid).ToList();
                        roleid = Role_[0].F_Id;
                        return db.FindEntity<SupplierEntity>(Supplier);
                    }
                    else
                    {
                        return null;
                    }
                }
                else
                {
                    var Supplier = Contact[0].SupplierID;
                    var rid = Contact[0].RoleId;
                    var Role_ = db.IQueryable<RoleEntity>(s => s.F_EnCode == rid).ToList();
                    roleid = Role_[0].F_Id;
                    return db.FindEntity<SupplierEntity>(Supplier);
                }                           
            }
        }

        public bool SubmitContactForm(SLContactEntity entity, string keyValue)
        {
            using (var db = new RepositoryBase())
            {
                if (!string.IsNullOrEmpty(keyValue))
                {
                    var list = db.IQueryable<SLContactEntity>(t => t.Phone == entity.Phone && t.F_Id != keyValue && (t.F_DeleteMark == null || t.F_DeleteMark == false));
                    if (list == null || list.Count() == 0)
                    {
                        entity.Modify(keyValue);
                        db.Update(entity);
                        return true;
                    }
                }
                else
                {
                    var list = db.IQueryable<SLContactEntity>(t => t.Phone == entity.Phone && (t.F_DeleteMark == null || t.F_DeleteMark == false));
                    if (list == null || list.Count() == 0)
                    {
                        entity.Create();
                        db.Insert(entity);
                        return true;
                    }
                }
                return false;
            }
        }

        public bool DelContactForm(string keyValue)
        {
            using (var db = new RepositoryBase())
            {
                var Contact = db.FindEntity<SLContactEntity>(keyValue);
                if (Contact.RoleId == "2001")
                {
                    var list=db.IQueryable<SLContactEntity>(t => t.SupplierID == Contact.SupplierID && t.RoleId == "2001" && (t.F_DeleteMark==null || t.F_DeleteMark==false));
                    if (list.Count() == 1)
                    {
                        return false;
                    }
                }
                if (Contact != null)
                {
                    Contact.Remove();
                    db.Update(Contact);
                }
                return true;
            }
        }


        public List<SupplierContactViewModel> GetContactList(string Uid)
        {
            using (var db = new RepositoryBase())
            {
                string sql = $@"SELECT 
                                T.F_Id,T.ContactName,T.Phone,T.Mobile,T.RoleId,T.Email
                                FROM SL_Contact T WHERE T.SupplierID='{Uid}' AND (T.F_DeleteMark is null or T.F_DeleteMark=0)";
                var list = db.FindList<SupplierContactViewModel>(sql);
                return list;
            }
        }

        public SupplierContactViewModel GetContact(string keyvalue)
        {
            using (var db = new RepositoryBase())
            {
                var Contact = db.FindEntity<SLContactEntity>(keyvalue);
                var ViewModel = new SupplierContactViewModel()
                {
                    F_Id = Contact.F_Id,
                    ContactName = Contact.ContactName,
                    Phone = Contact.Phone,
                    Mobile = Contact.Mobile,
                    RoleId = Contact.RoleId.ToString(),
                    Email = Contact.Email
                };
                return ViewModel;
            }
        }

        /// <summary>
        /// 注册供应商
        /// </summary>
        /// <param name="Name"></param>
        /// <param name="Phone"></param>
        /// <param name="Contact"></param>
        /// <returns></returns>
        public bool RegisterUser(string Name,string Phone,string Contact, string Vcard, string BL)
        {
            using (var db = new RepositoryBase().BeginTrans())
            {
                var list=db.IQueryable<SLContactEntity>(t => t.Phone == Phone && (t.F_DeleteMark == null || t.F_DeleteMark == false));
                if(list==null || list.Count() == 0)
                {
                    var supplier = new SupplierEntity();
                    supplier.Create();
                    supplier.name = Name;
                    supplier.the_contact = Contact;
                    supplier.phone = Phone;
                    supplier.Vcard = Vcard;
                    supplier.BusinessLicense = BL;
                    db.Insert(supplier);

                    var ContactModel = new SLContactEntity();
                    ContactModel.Create();
                    ContactModel.ContactName = Name;
                    ContactModel.Phone = Phone;
                    ContactModel.RoleId = "2001";
                    ContactModel.SupplierID = supplier.F_Id;
                    db.Insert(ContactModel);
                    db.Commit();
                    return true;
                }
                return false;
            }
        }
    }
}

